#!/bin/bash

if [ -z $1 ] # No hay primer argumento (largo 0)
    then
    dir=$(pwd)/
else
    if [ $1 == "-h" ] || [ $1 == "--help" ]
        then
        echo -e "\nCreateSymbolicLinks \n\nUsage: \ncreateSymbolicLinks [path to linked files] [target folder]\n\nCreates symbolic links to all the files (not folder or backups) \ncontained in the first argument (current folder if there is not). \nThe links are created in the second argument, the target folder \n(current folder if there is not). \n\nThe new symbolic links have the same name that the linked files, \nwhich creates a conflict if they are going to be created at the \nsame folder. Before any attempt to overwrite a file, a question \nis displayed. \n"
        exit -1
    fi
    if [ -d $1 ]
        then
        if [[ $1 != /* ]]
            then
            dir=$(pwd)/$1
        else
            dir=$1
        fi
    else
        echo "The folder $1 does not exist. See usage with -h or --help."
        exit 1
    fi
fi
if [[  $dir != */ ]]
    then
    dir=$dir/
fi

if [ -z $2 ] # No hay segundo argumento
    then
    OBJ=$(pwd)/
    else
    if [ -d $2 ]
        then
        if [[ $2 != /* ]]
            then
            OBJ=$(pwd)/$2
        else
            OBJ=$2
        fi
    else
        echo "The folder $2 does not exist. See usage with -h or --help."
        exit 1 
    fi
fi
if [[ $OBJ != */ ]]
    then
    OBJ=$OBJ/
fi

echo -e "In $OBJ folder will be created a symbolic links \nof the files presented in $dir. \n\nIs this your idea? (Yes/No)"
read tmpans
answer=$(echo "$tmpans" | tr '[:upper:]' '[:lower:]')
if [ "$answer" != "y" ] && [ "$answer" != "yes" ]; then
    echo "Ok, it isn't, next time think twice."
    exit 0
else
    echo 
    filesInDir=$(dir -1 -B $dir)
    for file in $filesInDir
        do
            if [ -h $OBJ$file ] || [ -e $OBJ$file ]
                then
                if [ "$answer" != "a" ] && [ "$answer" != "all" ]
                    then
                    if [ -h $OBJ$file ]
                        then
                        echo -e "The symbolic link $OBJ$file already exist. \nDo you want to delete it and create a new symbolic link? (Yes/All/No)"
                    fi
                    if [ -e $OBJ$file ]
                        then
                        echo -e "The file $OBJ$file already exist, not as symbolic link. \nDo you want to delete this file and create instead the symbolic link? (Yes/All/No)"
                    fi
                    read tmpans
                    answer=$(echo "$tmpans" | tr '[:upper:]' '[:lower:]')
                fi
                if [ "$answer" != "y" ] && [ "$answer" != "yes" ] && [ "$answer" != "a" ] && [ "$answer" != "all" ]
                        then
                        continue
                else
                    rm $OBJ$file
                fi
            fi
            ln -s $dir$file $OBJ
    done    
fi
